$(function (){

	//根据供应商的不同,在联系人框显示联系人的姓名
	$("#supplier_input").on("blur",function (){

		$.get("/products/findContactForSupplier",{supplier:$(this).val()},function (data){
			$("#contact_data").empty();
			$.each(data,function (i,item){
				$("#contact_data").append("<option value='"+item+"'></option>");
			})
		})
	})
	$("#supplier_input,#contact_input,#telephone_input,#brand_select_ipt,#variety_select_ipt,#type_input").on("focus",function (){
		$(this).val("");
	})

	//根据联系人姓名将联系方式显示在手机号框内
	$("#contact_input").on("blur",function (){
		$.get("/products/findTelephonesForContact",{contact:$(this).val()},function (data){
			$("#telephone_data").empty();
			$.each(data,function (i,item){
				$("#telephone_data").append("<option value='"+item+"' ></option>");
			})
		})
	})



	$("#product_table").on("blur","tr td .count_input",function (){
		//获取当前tr的序列
		var index = $(this).parents("tr").index();
		var number = $("tr .price_input:eq("+(index-1)+")").val()*$("tr .count_input:eq("+(index-1)+")").val();
		number= parseInt(number*100)/100;
		$("tr .money_input:eq(" + (index - 1) + ")").val(number);
	})

	//计算 数量*单价 将结果存放进金额
	$("#product_table").on("blur","tr td .price_input",function (){
		//获取当前tr的序列
		var index = $(this).parents("tr").index();
		var number = $("tr .price_input:eq("+(index-1)+")").val()*$("tr .count_input:eq("+(index-1)+")").val();
		number= parseInt(number*100)/100;
		$("tr .money_input:eq(" + (index - 1) + ")").val(number);
	})
	//点击添加产品按钮,table添加一行.
	$("#product_btn_add").on("click",function (){
		$("#product_table tbody").append(addTrMethod());
		// return false;
	})
	//删除选中行
	$("#product_btn_del").on("click",function (){
		//获取所有的选中框
		$("#product_table :checkbox:checked").each(function (){
			//遍历每一个选中框的tr所在的顺序
			var checkIndex = $(this).parents("tr").index();
			//通过顺序删除指定元素
			$("#product_table").find("tr:eq(" + checkIndex + ")").remove();
		})

		// return false;
	})
	//todo:提交数据


	$("#product_submit").on("click",function (){
		$("#variety_select").val();
		var supplier = $("#supplier_input").val();
		var warehouse_id = $("#warehouse_id span:eq(0)").html();
		console.log("warehouse_id"+warehouse_id);
		var products = $("#product_from").serializeArray();
		console.log(products);
		var list = [];
		var index = 0 ;
		var product = {
			supplier:supplier,
			contact:'',
			telephone:'',
			warehouseId:warehouse_id,
			brandName:'',
			varietyName:'',
			typeName:'',
			standard:'',
			units:'',
			count:'',
			price:'',
			money:'',
			remark:$(":text[name='remark']").val()
			,createTime:new Date()
		}
		$.each(products,function (i,item){
			switch (item.name){
				case "contact": product.contact = item.value;break;
				case "telephone": product.telephone = item.value;break;
				case "brandName": product.brandName = item.value;break;
				case "varietyName": product.varietyName = item.value;break;
				case "typeName": product.typeName = item.value;break;
				case "standard": product.standard = item.value;break;
				case "units": product.units = item.value;break;
				case "count": product.count = item.value;break;
				case "price": product.price = item.value;break;
				case "money":
					product.money = item.value;
					list[index]= product;
					product = {
						supplier:supplier,
						contact:'',
						telephone:'',
						warehouseId:warehouse_id,
						brandName:'',
						varietyName:'',
						typeName:'',
						standard:'',
						units:'',
						count:'',
						price:'',
						money:'',
						remark:$(":text[name='remark']").val(),
						createTime: new Date()
					}
					index++;
					break;
				default : break;
			}
		})
		var listStr = JSON.stringify(list);

		// confirm("添加成功");

		$.ajax({
			url:"/products/addList",
			contentType:"application/json;charset=utf-8",
			type:"post",
			data:listStr,
			success:function (data){
				if(data>=1){
					layui.use('layer', function(){ //独立版的layer无需执行这一句
						layer.msg('添加成功', {
							time:10000,
							btn: ['查看所有产品', '继续添加产品','打印入库单'],
							btnAlign: 'c',
							anim: 6,
							yes:function (index,layero){
								location.href="/products/list";
							},
							btn2:function (index,layero){
								location.href="/products/add";
							},btn3:function (index,layero){
								tableToExcel(listStr);
							}
						});
					});
				}
			}
		})

		return false;
	})
	// ajax 通过品种 ID,获取所有的类型,显示在下拉框
	$("#product_table").on("blur",'tr td .variety_input',function(){
		var varietyId = 0 ;

		var barietyValue= $(this).val();
		$("#variety_select option").each(function (i,item){
			if($(item).val() === barietyValue){
				varietyId = $(item).attr("data-id");
			}
		})
		if(varietyId!=0){
			$.post("/type/forVarietyId",{"varietyId":varietyId},function (data){
				$("#type_select").empty();
				$.each(data,function (i,item){
					$("#type_select").append("<option data-id='"+item.id+"' value='"+item.name+"'></option>");
				})
			})
		}
	})
	//ajax 通过品牌 ID 获取所有的品种,显示在下拉框.
	$("#product_table").on("blur",'tr td .brand_input',function (){
		var brandId = 0 ;
		//通过选中的内容,返回需要获取品牌的ID值
		var brandValue = $(this).val();
		$("#brand_select option").each(function (i,n){
			if ($(n).val() === brandValue){
				brandId = $(n).attr("data-id");
			}
		})
		//通过brandId的值动态生成对应品种到  #variety_select 元素中
		if(brandId != 0 ){
			$.post("/variety/forBrandId",{"brandId":brandId},function (data){
				$("#variety_select").empty();
				$("#type_select").empty();
				$.each(data,function (i,item){
					$("#variety_select").append("<option data-id='"+item.id+"' value='"+item.name+"'></option>");
				})
			})
		}
	})
})
//  动态添加的内容
function addTrMethod(){
	return "<tr>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<label class='label_checkbox'>\n" +
		"\t\t\t\t\t\t<input type='checkbox' class='checkbox_choose'  name='product_checkbox' >\n" +
		"\t\t\t\t\t</label>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' name='brandName' class='brand_input product_ipts' style='width: 200px;' placeholder='选择品牌' list='brand_select'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text'  name='varietyName' class='variety_input product_ipts' style='width: 200px;' placeholder='选择品种' list='variety_select'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' id='type_input' name='typeName' class='product_ipts' style='width: 200px;' placeholder='选择类型' list='type_select'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' class='product_ipts' name='standard'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' class='product_ipts' style='width: 60px;' name='units'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' class='count_input product_ipts' style='width: 60px;' name='count'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' class='price_input product_ipts' name='price'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t\t<td>\n" +
		"\t\t\t\t\t<input type='text' class='money_input product_ipts' name='money'>\n" +
		"\t\t\t\t</td>\n" +
		"\t\t\t</tr>";
}

//	配置打印信息
const tableToExcel = (listStr) => {
	// 要导出的json数据
	const jsonData = JSON.parse(listStr);

	var date = new Date(jsonData[0]['createTime']);

	var dateStr = date.getFullYear()+"-"+(date.getMonth()+1)+"-"+date.getDate()
	var fontSize1 = 18;
	var fontSize2 = 16;


	var startStr = "<tr><td style=\"font-size: 27px; text-align: center\" colspan=\"8\">石家庄福澈研磨科技有限公司入库单</td></tr>\n" +
		"\t\t<tr >\n" +
		"\t\t\t<td colspan='2' style=\"text-align: center;font-size: "+fontSize1+"px; font-weight: bold;\">供货单位</td>\n" +
		"\t\t\t<td colspan='6' style='font-size: "+fontSize2+"px;'>"+jsonData[0]['supplier']+"</td>\n" +
		"\t\t</tr>\n" +
		"\t\t<tr>\n" +
		"\t\t\t<td colspan='2'  style=\"text-align: center;font-size:"+fontSize1+"px;font-weight: bold;\">联系人</td>\n" +
		"\t\t\t<td colspan='2' style='font-size: "+fontSize2+"px;'>"+jsonData[0]['contact']+"</td>\n" +
		"\t\t\t<td colspan=''  style=\"text-align: center;font-size: "+fontSize1+"px;font-weight: bold;\">电话</td>\n" +
		"\t\t\t<td colspan='' style='font-size: "+fontSize2+"px;'>"+jsonData[0]['telephone']+"</td>\n" +
		"\t\t\t<td colspan=''  style=\"text-align: center;font-size: "+fontSize1+"px;font-weight: bold;\">日期</td>\n" +
		"\t\t\t<td colspan='' style='font-size: "+fontSize2+"px;'>"+dateStr+"</td>\n" +
		"\t\t</tr>\n" +
		"\t\t<tr>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;'>序号</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >品牌</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >品名</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >型号</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >规格</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >单价(元)</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >数量</th>\n" +
		"\t\t\t<th style='font-size: "+fontSize1+"px;' >金额</th>\n" +
		"\t\t</tr>";

	var num = 0;

	// 列标题
	let str = startStr;
	// 循环遍历，每行加入tr标签，每个单元格加td标签
	for(let i = 0 ; i < jsonData.length ; i++ ){

		str+='<tr>';

		str+="\t\t\t<td style='font-size: "+fontSize2+"px;' >"+(i+1)+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['brandName']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['varietyName']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['typeName']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['standard']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['count']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['price']+"</td>\n" +
		"\t\t\t<td style='text-align: center;font-size: "+fontSize2+"px;'>"+jsonData[i]['money']+"</td>\n";

		str+='</tr>';
		num+=parseFloat(jsonData[i]['money']);
	}

	console.log(num);


	var endStr = "<tr>\n" +
		"\t\t\t<td colspan='2'  style='text-align: center;font-size: "+fontSize1+"px;font-weight: bold;'>合计</td>\n" +
		"\t\t\t<td colspan='6'  style='font-size: "+fontSize2+"px;text-align: left'>"+num+"</td>\n" +
		"\t\t</tr>\n" +
		"\t\t<tr>\n" +
		"\t\t\t<td colspan='2' style='text-align: center;font-size: "+fontSize1+"px;font-weight: bold;'>备注</td>\n" +
		"\t\t\t<td colspan='6'style='font-size: "+fontSize2+"px;'>"+" "+jsonData[0]['remark']+"</td>\n" +
		"\t\t</tr>\n" +
		"\t\t<tr>\n" +
		"\t\t\t<td colspan='2' style='text-align: center;font-size: "+fontSize1+"px;font-weight: bold;'>制单</td>\n" +
		"\t\t\t<td colspan='2' style='font-size: "+fontSize2+"px;'></td>\n" +
		"\t\t\t<td colspan='1' style='text-align: center;font-size: "+fontSize1+"px;font-weight: bold;'>审核</td>\n" +
		"\t\t\t<td colspan='3' style='font-size: "+fontSize2+"px;'></td>\n" +
		"\t\t</tr>";

	str+=endStr;
	// Worksheet名
	const worksheet = 'Sheet1'
	const uri = 'data:application/vnd.ms-excel;base64,';

	// 下载的表格模板数据
	var template = '<html xmlns:o="urn:schemas-microsoft-com:office:office"  xmlns:x="urn:schemas-microsoft-com:office:excel"';
	template +=' xmlns="http://www.w3.org/TR/REC-html40">';
	template +=' <head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>';
	template +=' <x:Name>'+worksheet+'</x:Name>';
	template +=' <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>';
	template +=' </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->';
	template +=' </head><body><table border="1" width="700">'+str+'</table></body></html>';

	// 下载模板
	window.location.href = uri + base64(template);
};

// 输出base64编码
const base64 = s => window.btoa(unescape(encodeURIComponent(s)));


